package com.tools.scanner.viewmodel

import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.Observer
import androidx.lifecycle.OnceLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.tools.scanner.bean.AdInfo
import com.tools.scanner.bean.AppSettings
import com.tools.scanner.bean.ShareInfo
import com.tools.scanner.network.IServerApi
import com.tools.scanner.network.RetrofitImpl
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

object DataViewModel : ViewModel() {

    private val mApiServer = RetrofitImpl.createApiService(IServerApi::class.java)

    private var mAppSettings: AppSettings? = null
    private var isLoading = false
    private val mDefaultShareInfo = ShareInfo(
        "7aC97bOxIEFsbC1pbi1PbmUgVG9vbDogUVIgU2Nhbm5lciwgT0NSICYgUERGIENvbnZlcnRlciAoRnJlZSEp",
        "7aC87byfIFdoeSBDaG9vc2UgU2NhbkZsb3cgUHJvPyAgCuKchSBTY2FuIEFueSBRUiBDb2RlICYgRXh0cmFjdCBUZXh0ICAK4pyFIFRyYW5zbGF0ZSAxMDArIExhbmd1YWdlcyBmcm9tIEltYWdlcyAgCuKchSBDcmVhdGUgSEQgUERGcyBmcm9tIERvY3VtZW50cy9DYW1lcmEgIArinIUgTGlnaHR3ZWlnaHQgJiBPZmZsaW5lIFN1cHBvcnQgIAoK7aC97bOyIEdldCBJdCBOb3c6IGh0dHBzOi8vcGxheS5nb29nbGUuY29tL3N0b3JlL2FwcHMvZGV0YWlscz9pZD1jb20uc2NhbmZsb3cucHJv"
    )

    private val mAppSettingsLiveData = OnceLiveData<LoadStatus>()

    fun requestAppSetting() {
        if (isLoading) {
            return
        }

        isLoading = true
        viewModelScope.launch(Dispatchers.Main) {
            mAppSettingsLiveData.value = LoadStatus.LOADING

            withContext(Dispatchers.IO) {
                try {
                    mApiServer.getAppSetting().execute().body()?.let {
                        mAppSettings = it.data
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }

            val state = if (mAppSettings == null) {
                LoadStatus.FAIL
            } else {
                LoadStatus.SUCCESS
            }
            mAppSettingsLiveData.value = state
        }
    }

    fun getAdInfoList(): List<AdInfo>? {
        return mAppSettings?.adInfoList
    }

    fun getShareInfo(): ShareInfo {
        return mAppSettings?.shareInfo ?: mDefaultShareInfo
    }

    fun getAppSettings(): AppSettings? {
        return mAppSettings
    }

    fun subscribeAppSettingsEvent(owner: LifecycleOwner, observer: Observer<LoadStatus>) {
        mAppSettingsLiveData.observe(owner, observer)
    }

    enum class LoadStatus {
        LOADING,
        SUCCESS,
        FAIL
    }

}